package com.czy.form.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.czy.form.model.FormData;
import com.czy.form.model.FormInfo;
import com.czy.form.model.FormMeta;
import com.czy.form.service.FormService;
import com.czy.form.util.ResultMap;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/***
 * @ ClassName: FormController
 * @ Description: TODO
 * @ author：libi
 * @ date： 2020/2/1 14:16
 * @ version： V1.0.0
 * @ CopyRight：czy
 */

@RestController
@RequestMapping("/form")
public class FormController {

    @Autowired
    FormService formService;

    @GetMapping("/list")
    @JsonView(FormMeta.SimpleView.class)
    public ResultMap listFormInfo(){
        return ResultMap.success().setData(formService.listFormInfo());
    }

    @PostMapping("/save")
    public ResultMap saveFormInfo(String data){
        FormInfo formInfo = JSONUtil.toBean(data, FormInfo.class);
        formService.saveFormInfo(formInfo);
        return ResultMap.success();
    }

    @GetMapping("/get")
    public ResultMap getFormInfo(String formId){
        return ResultMap.success().setData(formService.getFormInfo(formId));
    }

    @PostMapping("/del")
    public ResultMap delFormInfo(String formId){
        formService.delFormInfo(formId);
        return ResultMap.success();
    }

    @GetMapping("/listData")
    @JsonView(FormMeta.SimpleView.class)
    public ResultMap listFormData(){
        return ResultMap.success().setData(formService.listFormData());
    }

    @PostMapping("/saveData")
    public ResultMap saveFormData(String data){
        FormData formData = JSONUtil.toBean(data, FormData.class);
        formService.saveFormData(formData);
        return ResultMap.success();
    }

    @GetMapping("/getData")
    public ResultMap getFormData(String dataId){
        return ResultMap.success().setData(formService.getFormData(dataId));
    }

    @PostMapping("/delData")
    public ResultMap delFormData(String dataId){
        formService.delFormData(dataId);
        return ResultMap.success();
    }

    @PostMapping("/upload")
    @ResponseBody
    public ResultMap upload(MultipartFile file){
        ResultMap result = ResultMap.success();
        if(file != null){
            result.put("name", file.getOriginalFilename());
            result.put("url", RandomUtil.randomNumbers(10));
            result.put("size", file.getSize());
        }
        return result;
    }
}
